package cn.codeforfun.auth;

import cn.codeforfun.auth.entity.AuthRequest;
import cn.codeforfun.auth.entity.AuthResponse;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.Date;

import static org.springframework.web.reactive.function.server.ServerResponse.ok;

/**
 * @author wangbin
 */
@Service
@Slf4j
public class AuthService {

    public Mono<ServerResponse> getAuth(ServerRequest serverRequest) {
        return serverRequest.bodyToMono(AuthRequest.class)
                .flatMap(s -> {
                    String url = "https://openapi.baidu.com/oauth/2.0/token?" +
                            "grant_type=authorization_code&" +
                            "code=%s&" +
                            "client_id=%s&" +
                            "client_secret=%s&" +
                            "redirect_uri=%s";
                    url = url.formatted(s.getCode(), s.getAppKey(), s.getSecretKey(), s.getCallbackUrl());
                    HttpResponse httpResponse = HttpUtil.createGet(url).setFollowRedirects(true).execute();
                    String body = httpResponse.body();
                    AuthResponse bean = JSONUtil.toBean(body, AuthResponse.class);
                    DateTime expiresAt = DateUtil.offset(new Date(), DateField.SECOND, bean.getExpiresIn());
                    bean.setExpiresAt(expiresAt);
                    return ok().bodyValue(bean);
                });
    }
}
